<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/10/22
 * Time: 16:01
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

namespace app\common\business;


use app\common\validate\Fabulous as ValObj;
use app\common\model\mysql\Fabulous as ModelObj;
use think\Exception;

class Fabulous extends Base
{
    /**
     * @var ValObj
     */
    protected ValObj $valObj;
    /**
     * @var ModelObj
     */
    protected ModelObj $modelObj;

    /**
     *
     */
    public function __construct()
    {
        $this->valObj = new ValObj();
        $this->modelObj = new ModelObj();
    }

    /**
     * @param int $theatre_id
     * @param string $openid
     * @return bool
     * @throws Exception
     */
    public function setFabulous(int $theatre_id = 0, string $openid = '')
    {
        //查询是否存在 存在则更新 不存在则创建
        try {
            $res = $this->modelObj->getFabulousByTheatreIdOpenid($theatre_id, $openid);
        } catch (\Exception $e) {
            throw new Exception("查询错误");
        }
        try {
            if ($res) {
                if($res['state'] == 0){
                    $state = 1;
                }else{
                    $state = 0;
                }
                $result = $res->save([
                    "state" => $state,
                    "update_time" => time()
                ]);
            } else {
                $result = $this->modelObj->insertAdd([
                    "theatre_id" => $theatre_id,
                    "openid" => $openid,
                    "state" => 1
                ]);
            }
        } catch (\Exception $e) {
            throw new Exception("操作失败");
        }
        return $result;
    }

    public function getFabulousByInfo(int $theatre_id = 0, string $openid = '')
    {
        try {
            $res = $this->modelObj->getFabulousByTheatreIdOpenid($theatre_id, $openid);
        } catch (\Exception $e) {
            throw new Exception("查询错误");
        }
        return $res;
    }
}